<template>
<div>
  <!-- 面包屑导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
  <el-card>
    <!-- 添加角色按钮区域 -->
    <el-row>
      <el-col>
        <el-button type="primary" @click="addroleDialogVisible = true">添加角色</el-button>
      </el-col>
    </el-row>
    <el-dialog title="添加角色" :visible.sync="addroleDialogVisible" width="50%">
    <el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRef" label-width="100px">
      <el-form-item label="用户编号" prop="roleId">
        <el-input v-model="roleForm.roleId"></el-input>
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="roleForm.roleDesc"></el-input>
      </el-form-item>
      <el-form-item>
        <template>
          <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
          <el-button size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
        </template>
      </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addroleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRole">确 定</el-button>
  </span>
</el-dialog>
    <!-- 角色列表区 -->
    <el-table :data="roleList">
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['bdbottom', index1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag closable @click="removeRightById (scope.row, item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级权限 -->
            <el-col :span="19">
              <el-row :class="[index2 === 0 ?'' : 'bdtop','vcenter']" v-for="(item2,index2) in item1.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag type="success" closable @click="removeRightById (scope.row, item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-row>
                    <el-col>
                      <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @click="removeRightById (scope.row, item3.id)">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="编号"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"  @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

<!-- 弹出权限对话框 -->
<el-dialog
  title="分配权限"
  :visible.sync="setRightDialogVisible"
  width="50%" @close="setRightDialogClosed">
  <el-tree :data="rightsList" ref="treeRef" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defualtKeys"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改权限对话框 -->
  <el-dialog title="修改用户对话框" :visible.sync="editDialog" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="编号" prop="roleId">
          <el-input v-model="editForm.roleId" disabled="disabled"></el-input>
        </el-form-item>
         <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      setRightDialogVisible: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defualtKeys: [],
      roleId: '',
      addroleDialogVisible: false,
      editDialog: false,
      roleForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      editRole: {},
      editForm: {},
      roleFormRules: {
        roleId: [
          { required: true, message: '请输入角色ID', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '角色的长度在2-10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色描述的长度在3-10个字符之间',
            trigger: 'blur'
          }
        ]
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '角色的长度在2-10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色描述的长度在3-10个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      // console.log(this.roleList)
    },
    async removeRightById (role, rightid) {
      const Resultconfirm = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (Resultconfirm !== 'confirm') return this.$message.info('取消删除该权限')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      role.children = res.data
    },
    async showSetRightDialog (role) {
      // 获取所有权限值
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('权限获取失败')
      this.rightsList = res.data
      this.getLeftKeys(role, this.defualtKeys)
      this.setRightDialogVisible = true
    },
    getLeftKeys (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item =>
        this.getLeftKeys(item, arr))
    },
    // 监听关闭对话框的关闭事件
    setRightDialogClosed () {
      this.defualtKeys = []
    },
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRightDialogVisible = false
    },
    saveRole () {
      this.$refs.roleFormRef.validate(async val => {
        console.log(val)
        if (!val) return
        const { data: res } = await this.$http.post('roles', this.roleForm)
        if (res.meta.status !== 201) return this.$message.error('角色添加失败')
        this.$message.success('角色添加成功')
        this.getRoleList()
        this.addroleDialogVisible = false
      })
    },
    async delRole (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      console.log(res.data)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.getRoleList()
      this.$message.success('用户删除成功')
    },
    editDialogClosed () {
      this.$refs.editForm.resetFields()
    }, // 展示编辑用户对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('用户信息查询失败')
      }
      this.editForm = res.data
      this.editDialog = true
    },
    editUserInfo () {
      this.$refs.editFormRef.validate(async val => {
        if (!val) return
        // 发起修改用户信息请求
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('更新用户信息失败')
        // 关闭对话框
        this.editDialog = false
        this.getRoleList()
        this.$message.success('更新用户信息成功')
      })
    }
  }
}

</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px
}
.bdtop {
  border-top: 1px solid #eee
}
.bdbottom {
  border-bottom: 1px solid #eee
}
.vcenter {
  display: flex;
  align-items: center
}
</style>
